package com.lagou.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String methodName = request.getParameter("methodName");
        String methodName = null;

        String contentType = request.getHeader("Content-Type");

        if("application/json;charset=utf-8".equals(contentType)) {
            String postJSON = getPostJSON(request);

            Map<String, Object> map = JSON.parseObject(postJSON, Map.class);

            request.setAttribute("map", map);

            methodName = (String) map.get("methodName");
        } else {
            methodName = request.getParameter("methodName");
        }


        if(null != methodName) {
            try {
                Class c = this.getClass();
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                Object invoke = method.invoke(this, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * POST请求格式为 application/json;charset=utf-8
     * 在这个方法中我们使用流的方式,获取到POST请求的数据
     * @param request
     * @return
     */
    private String getPostJSON(HttpServletRequest request) {

        try {
            BufferedReader reader = request.getReader();

            StringBuffer sb = new StringBuffer();

            String line = null;
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
